var ImageFile;
function listenFileSelect() {
    var fileInput = document.getElementById("mypicInput"); 

    fileInput.addEventListener('change', function (e) {
        ImageFile = e.target.files[0]; 
        var imageurl = URL.createObjectURL(ImageFile);
        console.log(imageurl);
        updateImage(imageurl);
    })
}
listenFileSelect();

function updateImage(imageurl) {
    const image = document.getElementById("mypic-goes-here"); 
    image.src = imageurl; 
}

function savePost() {
    
    var calorieData = document.getElementById('calorieInput').value;
    var details = document.getElementById('detailsText').value;
    var image = document.getElementById('mypicInput').files[0];

    const now = new Date();
    const dformatted = now.toLocaleString('en-US', {
        weekday: 'short', 
        year: 'numeric', 
        month: 'short', 
        day: 'numeric', 
        hour: 'numeric', 
        minute: 'numeric',
        second: 'numeric'
    });

    const editID = document.getElementById("editID").value;


    if (!editID) {
        var formData = {
            date: dformatted,      
            calories: calorieData,  
            details: details,
            imageName: image.name 
        }; 

        addToPostHistory(formData);
    }
    else {
        const user = JSON.parse(localStorage.getItem("loggedinUser"));
        const users = JSON.parse(localStorage.getItem("users"));
        const person = users.find(u => u.email === user["email"]);


        person.history[editID].calories = calorieData;
        person.history[editID].details = details;
        person.history[editID].date = dformatted;


        if (image) {
            person.history[editID].imageName = image.name;
        }


        localStorage.setItem("users", JSON.stringify(users));
        alert('Data updated successfully!');
        location.href="../history.html";
    }
}

function addToPostHistory(data) {
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    if (user) {
        var users = JSON.parse(localStorage.getItem("users"));
        var email = user["email"]; 
        const person = users.find(u => u.email === email);
        if (person.history === null) 
            person.history = []; 
      
        person.history.push(data);

        localStorage.setItem("users", JSON.stringify(users));

        addCountLocalStorage(data.calories);
        alert('Data saved successfully!');

    } else {
        console.log("No one is logged in");
    }
}
function addCountLocalStorage(value) {
    var user = JSON.parse(localStorage.getItem("loggedinUser"));
    var users = JSON.parse(localStorage.getItem("users"));
    const person = users.find(u => u.email === user["email"]);
    person.count = Number(person.count) + Number(value);
    localStorage.setItem("users", JSON.stringify(users));
}

function checkEdit() {
    var params = new URLSearchParams(window.location.search);
    const id = params.get("id");
    if (id) {
        const user = JSON.parse(localStorage.getItem("loggedinUser"));
        const users = JSON.parse(localStorage.getItem("users"));
        const person = users.find(u => u.email === user["email"]);

        document.getElementById("postTitle").innerHTML = "Edit your post from" + person.history[id].date;
        document.getElementById("postButton").innerHTML = "Save post";
        document.getElementById("calorieInput").value = person.history[id].calories;
        document.getElementById("detailsText").value = person.history[id].details;

        updateImage("../images/" + person.history[id].imageName);

        document.getElementById("editID").value = id;
    }
}
checkEdit();